<template>
  <el-container class="template-layout">
    <!-- 顶部查询 -->
    <el-header v-if="showSearchHeader">
      <zz-Search
          :searchOptions="searchOptions"
          :loading="loading"
          @getSearchData="getSearchData"
          @resetFields="resetFields"
      />
    </el-header>

    <el-main>
      <!-- 工具栏与右侧操作：表格尺寸/显示查询/列设置 -->
      <zz-PageBar>
        <template #buttons>
          <el-button type="primary" @click="addItem">{{ $t('common.add') }}</el-button>
          <el-button type="danger" @click="delItems" plain>{{ $t('common.delete') }}</el-button>
        </template>
        <template #right>
          <el-dropdown @command="handleSizeChange">
            <el-button :icon="'Switch'" circle />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="mini">{{ $t('table.mini') }}</el-dropdown-item>
                <el-dropdown-item command="small">{{ $t('table.small') }}</el-dropdown-item>
                <el-dropdown-item command="medium">{{ $t('table.medium') }}</el-dropdown-item>
                <el-dropdown-item command="large">{{ $t('table.large') }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button :icon="'Search'" circle @click="showSearchHeader = !showSearchHeader" />
          <el-button :icon="'Operation'" circle @click="showColumnSetting = true" />
        </template>
      </zz-PageBar>

      <!-- 表格 -->
      <zz-Table
          ref="tableRef"
          :key="tableKey"
          :data="tableData"
          :size="tabelSize"
          :loading="loading"
          :page="tablePage"
          :hasPage="true"
          @pageChange="pageChange"
      >
        <vxe-column type="checkbox" fixed="left" width="40" />
        <vxe-column type="seq" fixed="left" width="50" />

        <!-- 动态列渲染：根据 tableColumns -->
        <template v-for="column in tableColumns" :key="column.field">
          <vxe-column
            v-if="column.visible"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :width="150"
          >
            <template #default="{ row }">
              {{ row[column.field] }}
            </template>
          </vxe-column>
        </template>

        <!-- 操作列 -->
        <vxe-column :title="$t('common.operation')" :width="200" fixed="right">
          <template v-slot="{ row }">
            <zz-TableBtn type="text" :loading="btnLoading" @click="editItem(row)">{{ $t('common.edit') }}</zz-TableBtn>
            <zz-TableBtn type="text" :loading="btnLoading" @click="viewItem(row)">{{ $t('common.view') }}</zz-TableBtn>
            <zz-TableBtn type="error" :loading="btnLoading" @click="delItem(row)">{{ $t('common.delete') }}</zz-TableBtn>
          </template>
        </vxe-column>
      </zz-Table>
    </el-main>
  </el-container>

  <!-- 业务组件 -->
  <addTestDataTypes
      ref="addTestDataTypesRef"
      v-model="addTestDataTypesIsOpen"
      @query="query"
  ></addTestDataTypes>
  <!-- 列设置：使用本地存储，键名 test-data-types_columns -->
  <zz-ColumnSetting
      v-model="showColumnSetting"
      :columns="tableColumns"
      :default-columns="defaultTableColumns"
      storage-key="test-data-types_columns"
      list-id="test-data-types-column-list"
      drawer-class="test-data-types-column-setting-drawer"
      @confirm="handleColumnConfirm"
      @cancel="handleColumnCancel"
      @reset="handleColumnReset"
  />
</template>

<script setup>
import addTestDataTypes from './components/addTestDataTypes.vue'
import { computed, getCurrentInstance, onMounted, ref } from 'vue';
const { proxy } = getCurrentInstance();

// UI 状态
const showSearchHeader = ref(true);
const showColumnSetting = ref(false);
const loading = ref(false);
const btnLoading = ref(false);


// 初始化
const init = () => {
  // todo:
  loadColumnSettings();
}

// 查询模型与配置
const searchModel = ref({
  username: '',
  gender: '',
  description: '',
  birthDate: null,
  createdDatetime: null,
  loginTime: null,
  updatedAt: null,
  age: null,
  totalViews: null,
  height: null,
  weight: null,
  salary: null,
  localeValueStr: '',
});

const searchOptions = computed(() => ({
  model: searchModel,
  column: [
    {
      label: proxy.$t('test_data_types.username'),
      type: 'inputText',
      field: 'username',
    },
    {
      label: proxy.$t('test_data_types.gender'),
      type: 'inputText',
      field: 'gender',
    },
    {
      label: proxy.$t('test_data_types.description'),
      type: 'inputText',
      field: 'description',
    },
    {
      label: proxy.$t('test_data_types.birth_date'),
      type: 'datePicker',
      field: 'birthDate',
    },
    {
      label: proxy.$t('test_data_types.created_datetime'),
      type: 'datePicker',
      field: 'createdDatetime',
      dateType: 'datetime',
    },
    {
      label: proxy.$t('test_data_types.login_time'),
      type: 'timePicker',
      field: 'loginTime',
      timeType: 'time',
    },
    {
      label: proxy.$t('test_data_types.updated_at'),
      type: 'datePicker',
      field: 'updatedAt',
      dateType: 'datetime',
    },
    {
      label: proxy.$t('test_data_types.age'),
      type: 'inputNumber',
      field: 'age',
    },
    {
      label: proxy.$t('test_data_types.total_views'),
      type: 'inputNumber',
      field: 'totalViews',
    },
    {
      label: proxy.$t('test_data_types.height'),
      type: 'inputNumber',
      field: 'height',
      precision: 2,
      step: 0.1,
    },
    {
      label: proxy.$t('test_data_types.weight'),
      type: 'inputNumber',
      field: 'weight',
      precision: 2,
      step: 0.1,
    },
    {
      label: proxy.$t('test_data_types.salary'),
      type: 'inputNumber',
      field: 'salary',
      precision: 2,
      step: 0.1,
    },
    {
      label: proxy.$t('test_data_types.locale_value'),
      type: 'inputText',
      field: 'localeValueStr',
    },
  ],
}));

// 查询事件
const getSearchData = (val) => {
  searchModel.value = val;
  query('search');
};
// 重置查询表单
const resetFields = () => {
  searchModel.value = {
    username: '',
    gender: '',
    description: '',
  };
};

// 表格与分页
const tableData = ref([]);
const tablePage = ref({ pageNum: 1, pageSize: 15, total: 0 });
const tabelSize = ref('small');
const tableRef = ref(null);

// 处理表格大小变化
const handleSizeChange = (size) => { tabelSize.value = size; };

// 列配置与本地存储键
const STORAGE_KEY = proxy.$CONS.STORAGE_KEY;
const tableKey = ref(0);

// 当前列配置与默认列
const tableColumns = ref([
    {
      field: "username",
      title: proxy.$t('test_data_types.username'),
      visible: true,
      fixed: null,
    },
    {
      field: "gender",
      title: proxy.$t('test_data_types.gender'),
      visible: true,
      fixed: null,
    },
    {
      field: "description",
      title: proxy.$t('test_data_types.description'),
      visible: true,
      fixed: null,
    },
    {
      field: "birthDate",
      title: proxy.$t('test_data_types.birth_date'),
      visible: true,
      fixed: null,
    },
    {
      field: "createdDatetime",
      title: proxy.$t('test_data_types.created_datetime'),
      visible: true,
      fixed: null,
    },
    {
      field: "loginTime",
      title: proxy.$t('test_data_types.login_time'),
      visible: true,
      fixed: null,
    },
    {
      field: "updatedAt",
      title: proxy.$t('test_data_types.updated_at'),
      visible: true,
      fixed: null,
    },
    {
      field: "age",
      title: proxy.$t('test_data_types.age'),
      visible: true,
      fixed: null,
    },
    {
      field: "totalViews",
      title: proxy.$t('test_data_types.total_views'),
      visible: true,
      fixed: null,
    },
    {
      field: "height",
      title: proxy.$t('test_data_types.height'),
      visible: true,
      fixed: null,
    },
    {
      field: "weight",
      title: proxy.$t('test_data_types.weight'),
      visible: true,
      fixed: null,
    },
    {
      field: "salary",
      title: proxy.$t('test_data_types.salary'),
      visible: true,
      fixed: null,
    },
    {
      field: "localeValue",
      title: proxy.$t('test_data_types.locale_value'),
      visible: true,
      fixed: null,
    },
]);
const defaultTableColumns = ref([
      {
        field: "username",
        title: proxy.$t('test_data_types.username'),
        visible: true,
        fixed: null,
      },
      {
        field: "gender",
        title: proxy.$t('test_data_types.gender'),
        visible: true,
        fixed: null,
      },
      {
        field: "description",
        title: proxy.$t('test_data_types.description'),
        visible: true,
        fixed: null,
      },
      {
        field: "birthDate",
        title: proxy.$t('test_data_types.birth_date'),
        visible: true,
        fixed: null,
      },
      {
        field: "createdDatetime",
        title: proxy.$t('test_data_types.created_datetime'),
        visible: true,
        fixed: null,
      },
      {
        field: "loginTime",
        title: proxy.$t('test_data_types.login_time'),
        visible: true,
        fixed: null,
      },
      {
        field: "updatedAt",
        title: proxy.$t('test_data_types.updated_at'),
        visible: true,
        fixed: null,
      },
      {
        field: "age",
        title: proxy.$t('test_data_types.age'),
        visible: true,
        fixed: null,
      },
      {
        field: "totalViews",
        title: proxy.$t('test_data_types.total_views'),
        visible: true,
        fixed: null,
      },
      {
        field: "height",
        title: proxy.$t('test_data_types.height'),
        visible: true,
        fixed: null,
      },
      {
        field: "weight",
        title: proxy.$t('test_data_types.weight'),
        visible: true,
        fixed: null,
      },
      {
        field: "salary",
        title: proxy.$t('test_data_types.salary'),
        visible: true,
        fixed: null,
      },
      {
        field: "localeValue",
        title: proxy.$t('test_data_types.locale_value'),
        visible: true,
        fixed: null,
      },
]);

// 处理列设置确认
const handleColumnConfirm = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
  all['test-data-types_columns'] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};
// 处理列设置取消
const handleColumnCancel = () => { loadColumnSettings(); };
// 处理列设置重置
const handleColumnReset = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
  all['test-data-types_columns'] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};

// 加载已保存列设置
const loadColumnSettings = () => {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY))?.['test-data-types_columns'];
    if (saved) tableColumns.value = saved;
    tableKey.value += 1;
  } catch (e) {
    console.error(proxy.$t("table.loadColumnSettingsFailed"), e);
  }
};

// 查询
const query = async (mode) => {
  loading.value = true;
  if (mode === 'search') {
    searchModel.value.queryParam = {
      pageNum: 1,
      pageSize: 15,
      total: 0,
    }
  }
  // TODO: 接入测试管理查询接口，替换为真实 API
  let params = dealParams();
  let res = await proxy.$API.testDataTypesManagement.testDataTypes.queryWithPage.post(params);
  if (res.code === '01') {
    tableData.value = res.bizList;
    tablePage.value.total = res.total;
    tablePage.value.pageSize = res.pageSize;
  }
  loading.value = false;
};
// 处理查询参数
const dealParams = () => {
  let params = {
    ...searchModel.value,
  };

  // 其他的参数转化逻辑，如日期格式等
  return params
}

// 业务操作占位
const addTestDataTypesRef = ref(null)
const addTestDataTypesIsOpen = ref(false)
const addItem = () => {
  addTestDataTypesIsOpen.value = true
  addTestDataTypesRef.value.type = "add";
  addTestDataTypesRef.value.title = proxy.$t("function.addItem", {
    type: proxy.$t(`test_data_types.itself`),
  })
};
const delItems = async () => {
  const rows = tableRef.value?.getCheckboxRecords?.() || [];
  if (rows.length === 0) return proxy.$message.warning(proxy.$t("message.selectItemsToDelete"));
  let ids = rows.map((e) => e.id)
  proxy
    .$confirm(proxy.$t("message.confirmDelete"), proxy.$t("message.deleteConfirm"), {
      confirmButtonText: proxy.$t("common.confirm"),
      cancelButtonText: proxy.$t("common.cancel"),
      type: "warning",
    })
    .then(async () => {
      let res = await proxy.$API.testDataTypesManagement.testDataTypes.deleteBatch.post(ids);
      if (res.code === "01") {
        query("search");
        proxy.$message.success(proxy.$t("message.deleteSuccess"));
      } else {
        proxy.$message.error(res.msg || proxy.$t("message.deleteFailed"));
      }
    })
    .catch(() => {
      proxy.$message.info(proxy.$t("message.deleteCanceled"));
    });
};
const delItem = async (row) => {
  let id = row.id;
  proxy
    .$confirm(proxy.$t("message.confirmDelete"), proxy.$t("message.deleteConfirm"), {
      confirmButtonText: proxy.$t("common.confirm"),
      cancelButtonText: proxy.$t("common.cancel"),
      type: "warning",
    })
    .then(async () => {
      let res = await proxy.$API.testDataTypesManagement.testDataTypes.delete.get(id);
      if (res.code === "01") {
        query("search");
        proxy.$message.success(proxy.$t("message.deleteSuccess"));
      } else {
        proxy.$message.error(res.msg || proxy.$t("message.deleteFailed"));
      }
    })
    .catch(() => {
      proxy.$message.info(proxy.$t("message.deleteCanceled"));
    });
};
const viewItem = (row) => {
  addTestDataTypesIsOpen.value = true
  addTestDataTypesRef.value.type = 'view'
  addTestDataTypesRef.value.title = proxy.$t("function.viewItem", {
      type: proxy.$t(`test_data_types.itself`),
  })
  addTestDataTypesRef.value.model.id = row.id
};
const editItem = (row) => {
  addTestDataTypesIsOpen.value = true
  addTestDataTypesRef.value.type = 'edit'
  addTestDataTypesRef.value.title = proxy.$t("function.editItem", {
      type: proxy.$t(`test_data_types.itself`),
  })
  addTestDataTypesRef.value.model.id = row.id
};

// 翻页
const pageChange = (page) => {
  searchModel.value.queryParam.pageNum = page.currentPage
  searchModel.value.queryParam.pageSize = page.pageSize
  query()
}

onMounted(() => {
  init();
  query('search');
});
</script>

<style lang="less" scoped></style>